import { makeAutoObservable, runInAction } from 'mobx'
import { CosInfo } from '../api/globals'
import { waitForApisInitialized } from '../uitls/apiUtils'

class COSStore {
  config: CosInfo | null = null
  isLoading: boolean = false
  error: string | null = null

  constructor() {
    makeAutoObservable(this)
    this.init()
  }

  async init() {
    try {
      runInAction(() => {
        this.isLoading = true
        this.error = null
      })
      // 获取配置和临时凭证
      const config = await this.getCOSConfig()

      runInAction(() => {
        this.config = config
      })
    } catch (err) {
      runInAction(() => {
        this.error = err instanceof Error ? err.message : '未知错误'
      })
    } finally {
      runInAction(() => {
        this.isLoading = false
      })
    }
  }

  private async getCOSConfig(): Promise<CosInfo> {
    // 调用utils的api延迟加载waitForApisInitialized
    // 确保Apis已经初始化
    await import('../uitls/apiUtils').then(({ waitForApisInitialized }) => {
      return waitForApisInitialized()
    })

    try {
      const res = await Apis.cos.Config({})
      return res
    } catch (error) {
      console.error(error)
      throw error
    }
  }

  get isReady() {
    return !!this.config
  }
}

export default new COSStore()
